﻿using System;
using Volo.Abp;
using Volo.Abp.DependencyInjection;
using Joy.Erp.BasicArchives.SerialNumbers;
using Newtonsoft.Json;

namespace Joy.Erp.BasicArchives.Core.UniqueCodes
{
    public class SerialNumberSegment : ISegment, ITransientDependency
    {
        protected SerialNumberSegmentConfigrationObject ConfigrationObject { get; set; }

        public ISerialNumberManager SerialNumberManager { get; }

        public SerialNumberSegment(ISerialNumberManager serialNumberManager)
        {
            SerialNumberManager = serialNumberManager;
        }

        public void Init(string configration)
        {
            ConfigrationObject = JsonConvert.DeserializeObject<SerialNumberSegmentConfigrationObject>(configration);
        }

        public string GetCode(IUniqueCode entity)
        {
            var number = SerialNumberManager.NextAsync(entity.GetType().FullName, ConfigrationObject.Start, ConfigrationObject.Stride, ConfigrationObject.ResetInterval).Result;

            if (number >= Math.Pow(10, ConfigrationObject.Length))
            {
                throw new BusinessException("BasicArchives:005").WithData("Length", ConfigrationObject.Length);
            }

            return number.ToString().PadLeft(ConfigrationObject.Length, ConfigrationObject.Padding);
        }
    }
}
